package com.zry.fertilizer.ui.fragment

import android.content.Intent
import com.zry.fertilizer.MainActivity
import com.zry.fertilizer.R
import com.zry.fertilizer.adapter.ReceiveNoticeAdapter
import com.zry.fertilizer.animation.RecyclerViewUtilKt
import com.zry.fertilizer.been.ReceiveNotice
import com.zry.fertilizer.been.ResultBean
import com.zry.fertilizer.been.SendOutNotice
import com.zry.fertilizer.databinding.FragmentMessageBinding
import com.zry.fertilizer.retrofit.HttpServer
import com.zry.fertilizer.retrofit.ShowUserView
import com.zry.fertilizer.ui.activity.MessageInfoActivity
import com.zry.fertilizer.ui.base.BaseFragment
import com.zry.fertilizer.utils.ACacheUtil
import com.zry.fertilizer.utils.ToastUtil
import java.lang.Thread.sleep
import java.util.logging.Handler

class MessageFragment : BaseFragment(), ShowUserView {


    private var mainActivity: MainActivity? = null
    private var messageBinding: FragmentMessageBinding? = null
    private var recyclerViewUtilKt: RecyclerViewUtilKt? = null
    override fun setOnCreate() {
        mainActivity = activity as MainActivity
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_message
    }

    override fun initDataView() {
        messageBinding = fragmentDataBinding as FragmentMessageBinding
        recyclerViewUtilKt = RecyclerViewUtilKt(mainActivity!!, messageBinding!!.messageRecycler)
        recyclerViewUtilKt?.initRecyclerView()
        HttpServer(this).getNoticeUserList(ACacheUtil().getLoginInfo().userid,1, 999, mainActivity!!)

        messageBinding!!.messageSwipeRefresh.setOnRefreshListener {
            HttpServer(this).getNoticeUserList(ACacheUtil().getLoginInfo().userid,1, 999, mainActivity!!)
            android.os.Handler().postDelayed({
                messageBinding!!.messageSwipeRefresh.isRefreshing = false
            },1000)
        }
    }

    private fun initAdapter(receiveNoticeList: MutableList<ReceiveNotice>) {
        val receiveNoticeAdapter = ReceiveNoticeAdapter(R.layout.item_receive_notice, receiveNoticeList)
        recyclerViewUtilKt?.setAdapter(receiveNoticeAdapter)
        receiveNoticeAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(mainActivity!!, MessageInfoActivity::class.java)
            intent.putExtra("ReceiveNotice", receiveNoticeList[position])
            mainActivity!!.startActivity(intent)
        }
    }

    override fun toMainActivity(what: Int, data: Any) {
        when (what) {
            43 -> {
                val resultData = data as ResultBean<MutableList<ReceiveNotice>>
                if (resultData.State == "1") {
                    initAdapter(resultData.ResultData)
                } else {
                    ToastUtil.toast(mainActivity!!, resultData.Message)
                }
            }
        }
    }


}
